package com.zwj.interview.链表;

/**
 * @Author: Zwj
 * @Date: 2022/2/28 14:42
 */
public class 翻转区间内的节点 {

    public ListNode reverse(ListNode head, int m, int n) {
        if (m == 1) {
            return reverseN(head, n);
        }
        //翻转中间的节点，
        head.next = reverse(head.next, m - 1, n - 1);
        return head;
    }


    //翻转前n个节点

    /**
     *
     *  1->2->3->4->5
     *  1<-2<-3
     *  对于节点1,2来说，翻转后的关系就是head.next.next=head;
     *  将翻转后
     *  head.next=successor;
     */
    public ListNode reverseN(ListNode head, int n) {
        ListNode successor = null;
        if (n == 1) {
            successor = head.next;
            return head;
        }
        ListNode last = reverseN(head.next, n - 1);
        //下面两步是处理边界问题
        head.next.next = head;
        head.next = successor;
        return last;
    }





}